{{include './header.html'}}
<body>
  <div id="root">
    <div id="chat">
      <div id="room-name" class="name"><span>群聊(0)</span></div>
      <div class="right">
        <ul id="message">
        </ul>
      </div>
      <div class="input">
        <input id="input" type="text" placeholder="{{name}} 说点什么……">
        <button id="submit">发送</button>
        <img src="/public/svg/file.svg" class="icon-font-useful" id='toggle-upload'>
        <div class="file-load" style="display: none;">
          <input type="file" name="file" id="file" style="flex:1">
          <button id='upload' style="width:80px">发送</button>
        </div>
      </div>
    </div>
    <div id="members">
      <!-- 注意这里不能用模板引擎渲染，这里时机不对 -->
      <h4>成员列表</h4>
      <table id='user-list'>
        <tr><th>用户名</th><th><img src="/public/images/svip.gif"></th><th>在线</th><th>socket.id</th></tr>
        
      </table>
    </div>

  </div>
  <!-- <div id="particles-js"></div> -->
</body>

<script>
  // console.log(param);
  // particlesJS('particles-js', param);
  // saveAs(new URL('https://static.prts.wiki/music/music/act9d0d0/m_avg_dignified_combine.mp3'), 'blob.mp3')
  $(function () {
    var socket = io();
    let joined = false
    let client = {
      name: '',
      svip: true,
      online: true
    }
    let allUsers = []
    const name = $.cookie('username');
    const listBtn = document.querySelector('#room-name')
    const userSheet = document.querySelector('.users')
    const userList = document.querySelector('#user-list')
    const roomName = document.querySelector('#room-name')
    const uploadBtn = document.querySelector('#upload')
    const uploadTable = document.querySelector('.file-load')
    const uploadToggle = document.querySelector('#toggle-upload')
    uploadBtn.addEventListener('click', sendFile)
    $('#input').focus()
    // 将该用户加入聊天系统，并添加消息dom的函数
    var append = function () {
      let list = [];
      return function ($node) {
        let height = 0;
        $('#message').html('');
        list.push($node);
        list.forEach(element => {
          $('#message').append(element);
        });
        let lis = $('#message').children();
        for (let i = 0; i < lis.length; i++) {
          height += $(lis[i]).height();
        }
        if(height>350){
          $('#message').scrollTop(height-330);
        }
      }
    }
    let room = append();
    // 群聊列表切换显示回调
    uploadTable.addEventListener('click', toggleUploadTable)
    uploadToggle.addEventListener('click', toggleUploadTable)
    // 重写在线列表的函数
    const renderList = (users) => {
      console.log(users);
      roomName.children[0].textContent = `群聊(${users.length})`
      // 重写tr
      const lenLi = userList.children.length-1
      const lenUsers = users.length
      let i = 0
      for (; i < lenUsers; i++) {
        if (i >= lenLi) {
          const newTr = document.createElement('tr')
          userList.appendChild(newTr)
          newTr.addEventListener('change', (event) => {
            console.log('checkbox', event.target.checked);
            socket.emit('notify', allUsers[event.currentTarget.id], event.target.checked? 2 : 3);
          })
        }
        const tr = userList.children[i+1]
        const user = users[i]
        tr.style.display = 'table-row'
        tr.id = i
        tr.innerHTML = `<td >${getUserHead(user)}</td><td><input type="checkbox"></td><td>${user.online}</td><td>${user.id}</td>`
        tr.children[1].children[0].checked = user.svip
        console.log(user.svip, tr.children[1].children[0].checked);
      }
      for (; i < lenLi; i++) {
        userList.children[i+1].style.display = 'none'
      }
    }
    // 发送聊天信息函数
    function send() {
      if (!client) return
      var msg = $('#input').val();
      if (msg) {
        // socket发送消息
        socket.emit('message', client, msg);
        $('#input').val('');
      } else {
        alert('消息不能为空');
      }
      $('#input').focus()
    }
    // 通过 Fetch API 向服务器发送文件
    function sendFile(event) {
      if (!client) return
      const fileInput = document.querySelector("input[type='file']");
      let file = fileInput.files[0]
      if (file) {
        let formData = new FormData();
        let sendFileBtn = uploadTable.children[1]
        sendFileBtn.textContent = '发送中'
        sendFileBtn.disabled = true
        formData.append('file', fileInput.files[0]);
        fileInput.value = ''
        fetch('/upload', {
          method: 'POST',
          body: formData
        })
        .then((res) => res.text())  // 注意这里是一个 response 对象，需要异步转完text，再json.parse，得到真正的参数
        .then((data) => {
          const json = JSON.parse(data)
          socket.emit('file', client, json.originalname, json.fileName);
          sendFileBtn.textContent = '发送'
          sendFileBtn.disabled = false
        })
      } else {
        alert('请选择文件后再进行发送')
      }
    }
    function toggleUploadTable(event) {
      if (event.target == event.currentTarget) uploadTable.style.display = uploadTable.style.display == 'none' ? 'flex' : 'none'
    }
    function downloadFile(event) {
      const li = event.target.parentElement
      const realName = li.id
      // 设置自定义下载名以及默认方式下载：失败
      // let nowName = realName.split('-')
      // nowName.shift()
      // nowName = nowName.join('-')
      // let url = new URL(window.location.protocol + '//' + window.location.host + '/uploads/' + realName)
      // console.log(url, nowName);
      // saveAs(url, nowName)
      window.open(window.location.protocol + '//' + window.location.host + '/uploads/' + realName)
    }
    function getUserHead(user) {
      if (user.svip) {
        return `<img src="/public/images/svip.gif"><b class="svip-b">${user.name}</b>`
      } else {
        return `<b>${user.name}</b>`
      }
    }
    // 点击提交或者回车向服务器发送message事件
    $('#submit').click(send)
    $('#input').keydown(function (event) {
      if (event.which === 13) {
        send()
      }
    })
      
    // 监听服务端发送的消息，并作出反应
    // 这个就是收到服务器广播的关于聊天消息的回调
    socket.on('message', (user, msg) => {
      room($(`<li class="msg-li">${getUserHead(user)}：${msg}</li>`))
    });
    socket.on('file', (user, name, realName) => {
      const newLi = document.createElement('li')
      newLi.className = 'msg-li'
      newLi.innerHTML = `${getUserHead(user.name, true)}：${name}<button>下载</button>`
      newLi.id = realName
      newLi.children[1].addEventListener('click', downloadFile)
      room(newLi)
    });
    
    socket.on('notify', (user, type, users) => {
      console.log(user, type, users);
      switch (type) {
        case -1:  // 管理员
          // allUsers = users
        case 0:   // 加入
          if (!client && user.name == name) {
            // 本用户第一次加入
            room($(`<li class="msg-notify-li"><div class="msg-notify-div">欢迎 ${getUserHead(user)} 加入群聊</div></li>`))
            client = user
          } else if (user.name != name) {
            room($(`<li class="msg-notify-li"><div class="msg-notify-div">欢迎 ${getUserHead(user)} 加入群聊</div></li>`))
          }
          break;
        case 1:   // 离开
          room($(`<li class="msg-notify-li"><div class="msg-notify-div"> ${getUserHead(user)} 离开了群聊</div></li>`))
          break;
        case 2:   // 获得 svip 服务
          room($(`<li class="msg-notify-li"><div class="msg-notify-div"> ${getUserHead(user)} 已被管理员授予 <img src="/public/images/svip.gif"></div></li>`))
          break;
        case 3:   // 失去 svip 服务
          room($(`<li class="msg-notify-li"><div class="msg-notify-div"> ${getUserHead(user)} 已被管理员移除 <img src="/public/images/svip.gif"></div></li>`))
          break;
        default:
          break;
      }
      allUsers = users
      renderList(users)
    })
  });
</script>
</html>